--
-- @Author:      qinxugao
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 处理登出, 用户离线后缓存数据清除

local skynet = require "skynet"
local log = require "Log"
local ltime = require "ltime"
local NodeMessage = require "NodeMessage"

local AssertEx = AssertEx

local Logout = class("Logout")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function Logout:ctor(message,userObj)
	self.userObj = userObj
	self.logoutList = {}
	self.nodeMessage = NodeMessage.new()
	self.msg = message
	self:register()

	local function loop()
		-- local l_day = ltime.getuday(os.time())
		-- local l_week = ltime.getuweek(os.time())
		-- local l_month = ltime.getumonth(os.time())
		-- local l_minute = math.floor(ltime.getdaysec(os.time()) / 60)
		while true do			
			--离线队列处理
			self:loot(os.time())
			skynet.sleep(300)
		end
	end	
	skynet.fork(loop)
end


function Logout:register()
	self.msg:registerSelf("logout_req",handler(self,self.userLogout))

end


--离线10分钟后清除用户数据
function Logout:loot(curtime)
	local out_list = {}
	for playerid,out_time in pairs(self.logoutList) do
		if curtime >= out_time then 				
			table.insert(out_list,playerid) 
		end
	end

	for _,playerid in ipairs(out_list) do
		
		self:cut(playerid)		
		local bclear = self.userObj:clear(playerid)
		if bclear then 
			self.nodeMessage:sendService('.proxy', 'update_agent_user_list',playerid,nil)
			--清除全局服中用户数据
			self.nodeMessage:sendGlobal('set_user_info',playerid,nil)
		end
	end

end

function Logout:add(playerid)
	self.logoutList[playerid] = os.time() + 10*60
end

function Logout:cut(playerid)
	self.logoutList[playerid] = nil
end

--玩家登出
function Logout:userLogout(user,args)
	--
	local playerid = user.playerid
	print("####logout playerid =",playerid)
	--skynet.call(self.managerSvr, 'lua', 'logout',playerid)
	self.nodeMessage:callService('.proxy', 'logout',playerid)
	return {logout_res={
		succese = 1,
	}}
end



return Logout